<template>
  <div class="max-w-md mx-auto">
    <!-- 表单标题 -->
    <div class="text-center mb-8">
      <div class="w-16 h-16 bg-primary/10 rounded-full flex items-center justify-center mx-auto mb-4">
        <svg class="w-8 h-8 text-primary" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
        </svg>
      </div>
      <h2 class="text-2xl font-bold text-foreground mb-2">{{ t('login.createUser') }}</h2>
      <p class="text-text-secondary">{{ t('login.createUserDescription') }}</p>
    </div>

    <!-- 创建用户表单 -->
    <div class="bg-card border border-border rounded-lg p-6 shadow-sm">
      <form @submit.prevent="handleSubmit">
        <div class="space-y-4">
          <!-- 用户名输入 -->
          <div>
            <label for="username" class="block text-sm font-medium text-text-secondary mb-2">
              {{ t('login.username') }} <span class="text-destructive">*</span>
            </label>
            <div class="relative">
              <input
                id="username"
                v-model="username"
                type="text"
                maxlength="10"
                :disabled="loading"
                :class="[
                  'w-full px-4 py-3 bg-input-background border rounded-md text-foreground placeholder:text-text-muted focus:outline-none focus:ring-2 transition-colors disabled:opacity-50',
                  inputError
                    ? 'border-destructive focus:ring-destructive/20 focus:border-destructive'
                    : 'border-border focus:ring-primary focus:border-transparent'
                ]"
                :placeholder="t('login.usernamePlaceholder')"
                autocomplete="off"
                @input="validateUsername"
                @blur="validateUsername" />

              <!-- 输入状态图标 -->
              <div class="absolute right-3 top-1/2 transform -translate-y-1/2">
                <!-- 验证成功图标 -->
                <svg
                  v-if="username.trim() && !inputError"
                  class="w-5 h-5 text-success"
                  fill="none"
                  stroke="currentColor"
                  viewBox="0 0 24 24">
                  <path
                    stroke-linecap="round"
                    stroke-linejoin="round"
                    stroke-width="2"
                    d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>

                <!-- 验证失败图标 -->
                <svg
                  v-else-if="username.trim() && inputError"
                  class="w-5 h-5 text-destructive"
                  fill="none"
                  stroke="currentColor"
                  viewBox="0 0 24 24">
                  <path
                    stroke-linecap="round"
                    stroke-linejoin="round"
                    stroke-width="2"
                    d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
              </div>
            </div>

            <!-- 字符计数器 -->
            <div class="flex justify-between items-center mt-2">
              <div>
                <!-- 实时验证错误提示 -->
                <p v-if="inputError" class="text-destructive text-xs flex items-center">
                  <svg class="w-3 h-3 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path
                      stroke-linecap="round"
                      stroke-linejoin="round"
                      stroke-width="2"
                      d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                  </svg>
                  {{ inputError }}
                </p>
                <!-- 验证成功提示 -->
                <p v-else-if="username.trim()" class="text-success text-xs flex items-center">
                  <svg class="w-3 h-3 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
                  </svg>
                  {{ t('login.usernameValid') }}
                </p>
              </div>

              <!-- 字符计数 -->
              <span
                :class="[
                  'text-xs',
                  username.length > 8 ? 'text-warning' : 'text-text-secondary',
                  username.length >= 10 ? 'text-destructive font-medium' : ''
                ]">
                {{ username.length }}/10
              </span>
            </div>
          </div>

          <!-- 服务器错误提示 -->
          <div v-if="error && !inputError" class="p-4 bg-destructive/10 border border-destructive/20 rounded-lg">
            <div class="flex items-start">
              <div class="flex-shrink-0">
                <svg class="w-5 h-5 text-destructive mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path
                    stroke-linecap="round"
                    stroke-linejoin="round"
                    stroke-width="2"
                    d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
              </div>
              <div class="ml-3">
                <h4 class="text-destructive text-sm font-medium mb-1">{{ t('login.createFailed') }}</h4>
                <p class="text-destructive text-sm">{{ error }}</p>
              </div>
            </div>
          </div>

          <!-- 操作按钮 -->
          <div class="flex gap-3 pt-2">
            <button
              type="button"
              :disabled="loading"
              class="flex-1 py-3 px-4 border border-border rounded-md text-text-secondary bg-background hover:bg-accent hover:text-accent-foreground transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
              @click="$emit('cancel')">
              {{ t('common.cancel') }}
            </button>
            <button
              type="submit"
              :disabled="loading || !username.trim() || !!inputError"
              class="flex-1 py-3 px-4 bg-primary text-primary-foreground rounded-md hover:bg-primary-hover focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-2 transition-colors font-medium disabled:opacity-50 disabled:cursor-not-allowed">
              <span v-if="loading" class="flex items-center justify-center">
                <div class="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></div>
                {{ t('login.creating') }}
              </span>
              <span v-else>{{ t('login.createUser') }}</span>
            </button>
          </div>
        </div>
      </form>
    </div>

    <!-- 提示信息 -->
    <div class="mt-6 text-center">
      <p class="text-text-secondary text-sm">{{ t('login.createUserHint') }}</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue';

import { t } from '@/i18n';

interface Props {
  loading?: boolean;
  error?: string;
}

const props = withDefaults(defineProps<Props>(), {
  loading: false,
  error: ''
});

const emit = defineEmits<{
  submit: [username: string];
  cancel: [];
  'clear-error': [];
}>();

const username = ref('');
const inputError = ref('');

// 监听用户输入，清除服务器错误
watch(username, () => {
  if (props.error) {
    emit('clear-error');
  }
});

const handleSubmit = () => {
  // 先进行验证
  validateUsername();

  if (inputError.value) {
    return;
  }

  if (username.value.trim()) {
    emit('submit', username.value.trim());
  }
};

// 用户名验证函数
const validateUsername = () => {
  const trimmedUsername = username.value.trim();

  if (!trimmedUsername) {
    inputError.value = '';
    return;
  }

  // 长度验证
  if (trimmedUsername.length < 2) {
    inputError.value = t('validation.minLength').replace('{min}', '2');
    return;
  }

  if (trimmedUsername.length > 10) {
    inputError.value = t('validation.maxLength').replace('{max}', '10');
    return;
  }

  // 字符验证 - 只允许中文、英文、数字和下划线
  const validPattern = /^[\u4e00-\u9fa5a-zA-Z0-9_]+$/;
  if (!validPattern.test(trimmedUsername)) {
    inputError.value = t('login.usernameInvalid');
    return;
  }

  // 不能全是数字
  if (/^\d+$/.test(trimmedUsername)) {
    inputError.value = t('login.usernameNotAllNumbers');
    return;
  }

  // 验证通过
  inputError.value = '';
};

// 暴露重置方法
const reset = () => {
  username.value = '';
  inputError.value = '';
};

defineExpose({
  reset
});
</script>
